package com.lin.controller;

import com.lin.common.constant.CustomerServiceConstant;
import com.lin.common.error.CustomRuntimeException;
import com.lin.common.rest.ResMsg;
import com.lin.controller.req.OrderListReqMsg;
import com.lin.controller.req.OrderPayReqMsg;
import com.lin.controller.req.Sha1SignReqMsg;
import com.lin.controller.res.OrderPageResMsg;
import com.lin.pay.paypal.v2.RequestToMapUtil;
import com.lin.pay.wx.sdk.WXPayUtil;
import com.lin.pay.wx.service.WxService;
import com.lin.pay.wx.vo.OpenidResult;
import com.lin.po.TranslateSetup;
import com.lin.service.pay.OrderPayService;
import com.lin.service.pay.PayPalCheckoutService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@RestController
@RequestMapping("/msvc")
public class PayOrderController {
    private static final Logger log = LoggerFactory.getLogger(PayOrderController.class);

    @Autowired
    private PayPalCheckoutService payPalCheckoutService;
    @Autowired
    private WxService wxService;
    @Autowired
    private OrderPayService orderPayService;


    @PostMapping("/unified-order")
    public ResMsg<Map<String, String>> unifiedOrder(@Valid @RequestBody OrderPayReqMsg<TranslateSetup> reqMsg) throws CustomRuntimeException, UnsupportedEncodingException {
        Map<String, String> map = orderPayService.unifiedOrder(reqMsg);
        return ResMsg.ok(map);
    }

    @PostMapping("/executePayments")
    public ResMsg<Map<String, String>> executePayments(@Valid @RequestBody OrderPayReqMsg<TranslateSetup> reqMsg) throws CustomRuntimeException, UnsupportedEncodingException {
        Map<String, String> map = orderPayService.unifiedOrder(reqMsg);
        return ResMsg.ok(map);
    }
    @PostMapping("/listorder")
    public ResMsg<OrderPageResMsg> listorder(@Valid @RequestBody OrderListReqMsg reqMsg) throws CustomRuntimeException {
        OrderPageResMsg resMsg = orderPayService.orderlist(reqMsg);
        return ResMsg.ok(resMsg);
    }

    @RequestMapping("/wx-notify")
    public void wxNotity(HttpServletRequest request, HttpServletResponse response) {
        String xmlMsg = null;
        try {
            // 1.获取报文体
            xmlMsg = getBodyStr(request);
            log.info("接收微信交易结果通知，请求报文：" + xmlMsg);
            Map<String, String> m = WXPayUtil.xmlToMap(xmlMsg);
            String result = orderPayService.channelNotify(m);
            response.setContentType("application/xml;charset=utf-8");
            response.getWriter().write(initRspXml(result));
        } catch (Exception e) {
            log.error("请求通知报文:{}，微信结果通知异常信息：{}", xmlMsg, e);
        }
    }

    @RequestMapping("/ali-notify")
    public void aliNotity(HttpServletRequest request, HttpServletResponse response) {
        //TODO
        String xmlMsg = null;
        try {
            // 1.获取报文体
            xmlMsg = getBodyStr(request);
            log.info("接收微信交易结果通知，请求报文：" + xmlMsg);
            Map<String, String> m = WXPayUtil.xmlToMap(xmlMsg);
            String result = orderPayService.channelNotify(m);
            response.setContentType("application/xml;charset=utf-8");
            response.getWriter().write(initRspXml(result));
        } catch (Exception e) {
            log.error("请求通知报文:{}，微信结果通知异常信息：{}", xmlMsg, e);
        }
    }


    @RequestMapping("/payapl/success")
    public String success(HttpServletRequest request) throws IOException {
        log.info("success request is :\n {}",getBodyStr(request));
        return payPalCheckoutService.callback(RequestToMapUtil.getParameterMap(request));
    }

    @RequestMapping("/payapl/cancel")
    public String cancel(HttpServletRequest request) throws IOException {
        log.info("cancel request is :\n {}",getBodyStr(request));
        return payPalCheckoutService.callback(RequestToMapUtil.getParameterMap(request));
    }

    private String initRspXml(String result) {
        if (StringUtils.equals(result, CustomerServiceConstant.WXSUCCESS)) {
            return "<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>";
        } else {
            return "<xml><return_code>FAIL</return_code><return_msg>系统繁忙。</return_msg></xml>";
        }
    }

    /**
     * @param request
     * @return
     * @Description:读取报文内容
     */
    private String getBodyStr(HttpServletRequest request) throws IOException {
        StringBuilder body = new StringBuilder();
        BufferedReader br = request.getReader();
        String str = "";
        while ((str = br.readLine()) != null) {
            body.append(str);
        }
        return body.toString();
    }

    @GetMapping("/getopenid/{code}")
    public ResMsg<OpenidResult> getOpenId(@PathVariable String code) {
        return ResMsg.ok(wxService.getOpenId(code));
    }

    @GetMapping("/wxticket")
    public ResMsg<String> getTicket() throws CustomRuntimeException {
        return ResMsg.ok(wxService.getTicket());
    }

    @PostMapping("/sha1sigin")
    public ResMsg<String> getOpenId(@RequestBody Sha1SignReqMsg reqMsg) throws CustomRuntimeException {
        return ResMsg.ok(wxService.sha1sign(reqMsg.getSignStr()));
    }
}
